import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import { ApiException } from '../exceptions/api.exception';
/**
 * 异常过滤器
 * 使用异常过滤器实现统一错误处理横切面
 * 捕获HttpException，然后设置我们自己的响应逻辑
 * 异常过滤器就是实现了 ExceptionFilter 接口，并且用 @Catch 装饰器修饰的类
 */
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    // const status = exception.getStatus()

    if (exception instanceof ApiException) {
      response
        // .status(status)
        .json({
          errorCode: exception.getErrorCode(),
          errorMessage: exception.getErrorMessage(),
          date: new Date().toLocaleDateString(),
          path: request.url,
        });

    } else {
      response
        // .status(status)
        .json({
          statusCode: 1003,
          date: new Date().toLocaleDateString(),
          path: request.url,
          errorMessage:exception.message.error
        });
    }
  }
}
